﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ZJK.Models.ExtractManage
{
    using DB_NH.DB_Model.ZJK;
    using DB_NH;
    using NHibernate;
    using NHibernate.Criterion;

    /// <summary>
    /// ViewModel：为已选择的关联项目创建新的抽取记录
    /// </summary>
    public class vmNewExtractForSelectedProjects
    {
        /// <summary>
        /// 所选择的项目ID列表
        /// </summary>
        public string selectedProjetcIDs { get; set; }

        /// <summary>
        /// 抽取记录标题
        /// </summary>
        public string extractRecord_Title { get; set; }

        /// <summary>
        /// 选定的项目
        /// </summary>
        public List<vmProject> extractRecord_selectedProjects { get; set; }

        /// <summary>
        /// 根据项目ID，获取并绑定项目列表信息
        /// </summary>
        public void getProjects()
        {
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        //获取数据库项目列表
                        var _projs = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                            .Where(c => c.is_valid == 1 && c.is_leaf == 1 && c.proj_id.IsIn(this.selectedProjetcIDs.Split(new char[] { ',' })))
                            .OrderBy(c => c.proj_code).Asc()
                            .List();
                        transaction.Commit();

                        //拼凑ViewModel项目列表
                        if (this.extractRecord_selectedProjects != null)
                        {
                            this.extractRecord_selectedProjects.Clear();
                        }
                        else
                        {
                            this.extractRecord_selectedProjects = new List<vmProject>();
                        }

                        foreach (var _p in _projs)
                        {
                            vmProject _vmp = new vmProject()
                            {
                                projectCode = _p.proj_code,
                                projectId = _p.proj_id,
                                projectName = _p.proj_name
                            };

                            this.extractRecord_selectedProjects.Add(_vmp);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (transaction.IsActive) transaction.Rollback();
                        //throw new Exception(ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 抽取结果记录列表：是否参加评标标志
        /// </summary>
        public string extractRecord_details_IsOK { get; set; }

        /// <summary>
        /// 抽取结果记录列表：抽取过程描述
        /// </summary>
        public string extractRecord_details_Describe { get; set; }

        /// <summary>
        /// 抽取结果记录列表：抽取类型（专业专家、商务专家）
        /// </summary>
        public string extractRecord_details_Type { get; set; }

        /// <summary>
        /// 抽取结果记录列表：专家ID
        /// </summary>
        public string extractRecord_details_ExpertId { get; set; }

        /// <summary>
        /// 保存抽取记录
        /// </summary>
        /// <param name="OP_UserName">操作的用户名参数</param>
        public void saveExtract(string OP_UserName)
        {
            if (string.IsNullOrEmpty(OP_UserName))
            {
                throw new Exception("操作用户未指定。");
            }

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 1、生成一条新的抽取记录
                        DB_NH.DB_Model.ZJCQ.ZJ_extract _rec = new DB_NH.DB_Model.ZJCQ.ZJ_extract()
                        {
                            extract_date = DateTime.Today,
                            title = this.extractRecord_Title
                        };
                        #endregion

                        #region 2、获取当前操作用户信息，设置抽取记录操作员信息
                        string _this_user_name_en = OP_UserName;
                        //处理用户名称，将域名去掉
                        if (_this_user_name_en.IndexOf('\\') > 0)
                        {
                            _this_user_name_en = _this_user_name_en.Substring(_this_user_name_en.IndexOf('\\') + 1);
                        }

                        var _this_user = session.QueryOver<DB_NH.DB_Model.ywxt.t_sys_user>()
                            .Where(c => c.is_valid == 1 && c.user_truename_en == _this_user_name_en)
                            .SingleOrDefault();
                        if (_this_user != null)
                        {
                            _rec.user = _this_user;
                        }
                        else
                        {
                            throw new Exception("操作用户信息失败。");
                        }
                        #endregion

                        #region 3、根据当前抽取关联的项目信息，设置抽取记录的所属项目
                        var _projs = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                            .Where(c => c.is_valid == 1 && c.is_leaf == 1 && c.proj_id.IsIn(this.selectedProjetcIDs.Split(new char[] { ',' })))
                            .OrderBy(c => c.proj_code).Asc()
                            .List();
                        foreach (var _p in _projs)
                        {
                            _rec.zj_extract_projects.Add(_p);
                            _p.proj_extracts.Add(_rec);
                            //session.SaveOrUpdate(_p);
                        }

                        //4、循环deitails，生成details数据，并关联到抽取记录
                        var _ExpertIds = this.extractRecord_details_ExpertId.Split(new char[] { ',' });
                        var _Describes = this.extractRecord_details_Describe.Split(new char[] { ',' });
                        var _IsOKs = this.extractRecord_details_IsOK.Split(new char[] { ',' });
                        var _Types = this.extractRecord_details_Type.Split(new char[] { ',' });

                        if (_ExpertIds.Length != _Describes.Length || _Describes.Length != _IsOKs.Length || _IsOKs.Length != _Types.Length)
                        {
                            //数组的维度不符合，提示错误
                            throw new Exception("抽取的专家记录信息错误，请确认参数数量是否匹配。");
                        }
                        else
                        {
                            for (int i = 0; i < _ExpertIds.Length; i++)
                            {
                                //获取专家信息
                                var _exp = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                    .Where(c => c.IsValid == 1 && c.Id == _ExpertIds[i])
                                    .SingleOrDefault();

                                if (_exp != null)
                                {
                                    //生成新的抽取详细记录
                                    DB_NH.DB_Model.ZJCQ.ZJ_extract_detail _detail = new DB_NH.DB_Model.ZJCQ.ZJ_extract_detail()
                                    {
                                        expert = _exp,
                                        extract = _rec,
                                        order_flag = i,
                                        un_selected_msg = _Describes[i],
                                        zj_company = _exp.zj_company,
                                        zj_idcard_number = _exp.zj_idcard_number,
                                        zj_mail_address = _exp.zj_mail_address,
                                        zj_mobile = _exp.zj_mobile,
                                        zj_name = _exp.zj_name,
                                        zj_position = _exp.zj_position,
                                        zj_professional = _exp.zj_professional,
                                        zj_sex = _exp.zj_sex,
                                        zj_tele_home = _exp.zj_tele_home,
                                        zj_tele_work = _exp.zj_tele_work,
                                        zj_title = _exp.zj_title,
                                        zj_type_name = _Types[i]
                                    };

                                    if (_IsOKs[i] == "Y")
                                    {
                                        _detail.is_selected = 1;
                                    }
                                    else
                                    {
                                        _detail.is_selected = 0;
                                    }
                                    session.SaveOrUpdate(_detail);
                                    _rec.details.Add(_detail);
                                }
                                else
                                {
                                    throw new Exception("抽取专家记录信息中，第" + i.ToString() + "条记录错误：没找到相应的专家记录。");
                                }
                            }
                        }
                        #endregion

                        #region 保存数据记录
                        session.SaveOrUpdate(_rec);
                        transaction.Commit();
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        if (transaction.IsActive) transaction.Rollback();
                        throw ex;
                    }
                }
            }
        }
    }


}